<template>
  <u-popup 
    :show="show" 
    @close="onClose"
    mode="bottom"
    :round="20"
    :closeable="false"
  >
    <view class="calendar-popup">
      <view class="calendar-header">
        <text class="header-action" @click="viewAll">查看所有</text>
        <text class="calendar-title">预招岗位日历</text>
        <u-icon name="close" size="22" color="#999999" class="header-close" @click="onClose" />
      </view>
      <view class="calendar-content">
        <!-- 月份导航 -->
        <view class="month-nav">
          <view class="nav-btn" @click="prevMonth">
            <u-icon name="arrow-left" size="16" color="#666666"></u-icon>
          </view>
          <text class="month-text">{{ currentYear }}年{{ currentMonth }}月</text>
          <view class="nav-btn" @click="nextMonth">
            <u-icon name="arrow-right" size="16" color="#666666"></u-icon>
          </view>
        </view>
        <!-- 星期标题 -->
        <view class="weekdays">
          <view class="weekday" v-for="day in weekdays" :key="day">{{ day }}</view>
        </view>
        <!-- 日历网格 -->
        <view class="calendar-grid">
          <view 
            v-for="(date, index) in calendarDates" 
            :key="index"
            class="calendar-day"
            :class="{
              'other-month': !date?.currentMonth,
              'selected': isSelectedDate(date),
              'today': isToday(date),
              'disabled': isDisabled(date),
              'has-jobs': hasJobs(date)
            }"
            @click="selectDate(date)"
          >
            <view class="day-content">
              <template v-if="date?.currentMonth && hasJobs(date)">
                <view class="date-pill">{{ formatDisplayDate(date.date) }}</view>
                <view class="job-pill">{{ getJobCount(date) }}岗</view>
              </template>
              <template v-else-if="date?.currentMonth">
                <text class="day-text">{{ formatDisplayDate(date.date) }}</text>
                <text class="no-job-text">暂无</text>
              </template>
              <template v-else>
                <!-- 非本月，保持空白布局 -->
                <text class="day-text" style="opacity:0;">00-00</text>
              </template>
            </view>
          </view>
        </view>
      </view>
      <!-- 底部提示 -->
      <view class="calendar-tip">
        <text class="tip-text">*温馨提示: 点击日历可筛选对应日期预招岗位!</text>
      </view>
    </view>
  </u-popup>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue'
import { jobApi } from '@/api/api-helper.js'
import { userStore } from '@/stores/userStore'

const props = defineProps({
  show: Boolean,
  jobDataByDate: {
    type: Object,
    required: true
  },
  year: {
    type: Number,
    default: 2025
  },
  month: {
    type: Number,
    default: 7
  },
  modelValue: String // 选中的日期（如07月30日）
})
const emit = defineEmits(['update:show', 'update:modelValue', 'select'])

const weekdays = ref(['日', '一', '二', '三', '四', '五', '六'])
const calendarDates = ref<any[]>([])
const currentYear = ref(new Date().getFullYear())
const currentMonth = ref(new Date().getMonth() + 1)
const selectedDateObj = ref<Date | null>(null) // 默认不选中任何日期
const dateCountMap = ref<Record<string, number>>({})

watch(() => props.show, (val) => {
  if (val) {
    generateCalendarDates()
    fetchMonthData()
  }
})

function onClose() {
  emit('update:show', false)
}

function generateCalendarDates() {
  const dates: any[] = []
  const firstDay = new Date(currentYear.value, currentMonth.value - 1, 1)
  const startDate = new Date(firstDay)
  startDate.setDate(startDate.getDate() - firstDay.getDay())
  for (let i = 0; i < 42; i++) {
    const date = new Date(startDate)
    date.setDate(startDate.getDate() + i)
    dates.push({
      date: date,
      day: date.getDate(),
      currentMonth: date.getMonth() === currentMonth.value - 1,
      year: date.getFullYear(),
      month: date.getMonth() + 1
    })
  }
  calendarDates.value = dates
}

function prevMonth() {
  if (currentMonth.value === 1) {
    currentMonth.value = 12
    currentYear.value--
  } else {
    currentMonth.value--
  }
  generateCalendarDates()
  fetchMonthData()
}

function nextMonth() {
  if (currentMonth.value === 12) {
    currentMonth.value = 1
    currentYear.value++
  } else {
    currentMonth.value++
  }
  generateCalendarDates()
  fetchMonthData()
}

function selectDate(date: any) {
  // 仅当当月且有岗位时才响应
  if (!date || !date.currentMonth || !hasJobs(date)) {
    return
  }
  selectedDateObj.value = date.date
  const display = formatDisplayDate(date.date)
  emit('update:modelValue', display)
  emit('select', display, date.date)
  emit('update:show', false)
}

function isSelectedDate(date: any) {
  if (!date || !date.date || !selectedDateObj.value) return false
  return date.date.getTime() === selectedDateObj.value.getTime()
}

function isToday(date: any) {
  if (!date || !date.date) return false
  const today = new Date()
  return date.date.getDate() === today.getDate() && 
    date.date.getMonth() === today.getMonth() && 
    date.date.getFullYear() === today.getFullYear()
}

function isDisabled(date: any) {
  // 允许选择所有日期
  return false
}

function hasJobs(date: any) {
  if (!date || !date.date || !date.currentMonth) return false
  const key = formatDateKey(date.date)
  return Boolean(dateCountMap.value[key])
}

function getJobCount(date: any) {
  if (!date || !date.date || !date.currentMonth) return 0
  const key = formatDateKey(date.date)
  return dateCountMap.value[key] || 0
}

function formatDateKey(date: Date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function formatDisplayDate(date: Date) {
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${month}-${day}`
}

function viewAll() {
  emit('select', 'all')
  emit('update:show', false)
}
// 調用接口獲取當月數據並按天彙總
async function fetchMonthData() {
  try {
    const openId = userStore.getOpenId && userStore.getOpenId()
    
    // 使用新的getDateCount接口獲取崗位數量統計
    const res: any = await jobApi.getDateCount({
      year: currentYear.value,
      month: currentMonth.value,
      openId
    })
    
    const map: Record<string, number> = {}
    if (res && res.code === 200) {
      // 根據實際返回的數據格式處理
      const list = (res.data && res.data) || []
      list.forEach((item: any) => {
        if (item.F_HireStartDate && typeof item.num === 'number') {
          // 解析日期字符串，格式為 "2025-08-13T00:00:00"
          const dateStr = item.F_HireStartDate.split('T')[0] // 提取日期部分 "2025-08-13"
          map[dateStr] = item.num
        }
      })
    }
    
    // 如果新接口沒有數據，回退到原來的邏輯
    if (Object.keys(map).length === 0) {
      const fallbackRes: any = await jobApi.getListToApp({
        currentPage: 1,
        pageSize: 200,
        type: 'ready', // 预招岗位
        order: 'signUpPersons',
        openId
      })
      
      if (fallbackRes && fallbackRes.code === 200) {
        const list = (fallbackRes.data && fallbackRes.data.list) || []
        list.forEach((item: any) => {
          const ts = item.hireStartDate || item.hireDate || item.createdAt
          if (!ts) return
          const d = new Date(ts)
          if (d.getFullYear() === currentYear.value && (d.getMonth() + 1) === currentMonth.value) {
            const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
            map[key] = (map[key] || 0) + 1
          }
        })
      }
    }
    
    dateCountMap.value = map
  } catch (e) {
    console.error('獲取崗位數量統計失敗:', e)
    dateCountMap.value = {}
  }
}
</script>

<style lang="scss" scoped>
/* 复用原有日历弹窗样式 */
.calendar-popup {
  background-color: #FFFFFF;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx 24rpx; /* 減少上下與左右留白 */
  min-height: 520rpx; /* 整體高度略降 */
}
.calendar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12rpx; /* 標題與內容距離縮短 */
  .header-action {
    font-size: 26rpx;
    color: var(--u-primary);
  }
  .calendar-title {
    font-size: 30rpx;
    font-weight: 600;
    color: #333333;
  }
  .header-close { padding: 10rpx; }
}
.calendar-content {
  .calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 8rpx;
    margin-top: 12rpx; /* 日曆與星期行距縮短 */
  }
  .calendar-day {
    aspect-ratio: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8rpx;
    position: relative;
    .day-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
    }
    .date-pill {
      margin-top: 8rpx;
      font-size: 22rpx;
      color: #FF6B35;
      background: #FFECE2;
      border-radius: 10rpx;
      padding: 6rpx 10rpx;
      line-height: 1;
    }
    .day-text {
      font-size: 22rpx;
      color: #333333; /* 無崗位時日期黑色 */
      margin-top: 8rpx;
    }
    .job-pill {
      margin-top: 6rpx;
      font-size: 20rpx;
      color: #FF6B35;
      background: #FFF6F1;
      border: 1rpx solid rgba(255,107,53,0.28);
      border-radius: 10rpx;
      padding: 4rpx 8rpx;
      line-height: 1;
    }
    .no-job-text {
      font-size: 20rpx;
      color: #BFBFBF; /* 更中性灰 */
      margin-top: 4rpx;
    }
    &.other-month {
      .day-text {
        color: #CCCCCC;
      }
    }
    &.has-jobs { }
    &.no-jobs {
      .day-text {
        color: #333333;
      }
      &.selected {
        background-color: var(--u-primary);
        border: 2rpx solid var(--u-primary);
        .day-text {
          color: #FFFFFF;
        }
      }
    }
    &.today {
      &.has-jobs {
        background-color: #FFF5F0;
        border: 2rpx solid var(--u-primary);
        .day-text {
          color: var(--u-primary);
          font-weight: bold;
        }
      }
    }
    &.disabled {
      .day-text {
        color: #CCCCCC;
      }
    }
  }
}
.month-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 18rpx; /* 月份導航與日曆距離縮短 */
  .nav-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background-color: #F5F5F5;
  }
  .month-text {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
  }
}
.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8rpx;
  margin-bottom: 20rpx;
  .weekday {
    aspect-ratio: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    color: #999999;
    font-weight: 500;
  }
}
.calendar-tip {
  margin-top: 30rpx;
  text-align: center;
  .tip-text {
    font-size: 24rpx;
    color: #FF4444;
    line-height: 1.4;
  }
}
</style> 